//
//  SecurityStatisticsView.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/5/19.
//

import Foundation
import UIKit

protocol SecurityStatisticsViewDelegate: AnyObject {
    func handleLzqkSelected(_ modal: TaskDeptRateModal) // 在岗情况
    func handleZgqkSelected(_ modal: BaglByDeptWdModel) // 履职情况
}

class SpsLzqkView: UIView {
    var isMore = false {
        didSet {
            reloadLzqk()
        }
    }
        
    var lzqkDatas: [TaskDeptRateModal] = []
    
    weak var sDelegate: SecurityStatisticsViewDelegate?

    // MARK: - Datas
    
    @objc func loadMore() {
        self.isMore = true
    }
    
    @objc func onSelectedLzqk(_ sender: UIControl) {
        let item = lzqkDatas[sender.tag]
        
        sDelegate?.handleLzqkSelected(item)
    }
    
    func reloadData(withModels wdList: [TaskDeptRateModal]?) {
        self.lzqkDatas = wdList ?? []
        reloadLzqk()
    }
    
    func reloadLzqk() {
        removeAllSubViews()
                
        var lastI: TaskCompletionRateItemView?
        
        var sortDatas: [TaskDeptRateModal] = []
        
        for (index, record) in lzqkDatas.enumerated() {
            if index < 5 {
                sortDatas.append(record)
            }
        }
        
        if isMore == true {
            sortDatas.removeAll()
            sortDatas.append(contentsOf: lzqkDatas)
        }
        
        for (index, record) in sortDatas.enumerated() {
            let itemV = TaskCompletionRateItemView()    // 网点名称
            itemV.reloadData(withModal: record)
            itemV.ctl.tag = index
            itemV.ctl.addTarget(self, action: #selector(onSelectedLzqk), for: .touchUpInside)
            addSubview(itemV)
            if index == sortDatas.count - 1 {
                itemV.snp.makeConstraints { make in
                    make.left.right.equalToSuperview()
                    if lastI == nil {
                        make.top.equalTo(self.snp.top).offset(20)
                    } else {
                        make.top.equalTo(lastI!.snp.bottom).offset(20)
                    }
                    if (lzqkDatas.count <= 5 || isMore == true) {
                        make.bottom.equalToSuperview()
                    }
                }
            } else {
                itemV.snp.makeConstraints { make in
                    make.left.right.equalToSuperview()
                    if lastI == nil {
                        make.top.equalTo(self.snp.top).offset(20)
                    } else {
                        make.top.equalTo(lastI!.snp.bottom).offset(20)
                    }
                }
            }
            lastI = itemV
        }
        
        if lzqkDatas.count > 5 && isMore == false {
            let moreBtn = UIButton(type: .custom)
            moreBtn.setTitleColor(.hex("#B1B1B1"), for: .normal)
            moreBtn.setTitle("查看更多", for: .normal)
            moreBtn.titleLabel?.font = .systemFont(ofSize: 14)
            moreBtn.addTarget(self, action: #selector(loadMore), for: .touchUpInside)
            addSubview(moreBtn)
            moreBtn.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(lastI!.snp.bottom).offset(20)
                make.height.equalTo(20)
                make.bottom.equalToSuperview()
            }
        }
    }
}

class SpsZgqkView: UIView {
    var isMore = false {
        didSet {
            reloadZgqk()
        }
    }
        
    var zgqkDatas: [BaglByDeptWdModel] = [] // 在岗
    
    weak var sDelegate: SecurityStatisticsViewDelegate?
    
    // MARK: - Datas
    
    @objc func loadMore() {
        self.isMore = true
    }
    
    @objc func onSelectedZgqk(_ sender: UIControl) {
        let item = zgqkDatas[sender.tag]
        sDelegate?.handleZgqkSelected(item)
    }
    
    // 在岗情况
    func reloadData(withModels wdList: [BaglByDeptWdModel]?) {
        self.zgqkDatas = wdList ?? []
        reloadZgqk()
    }

    func reloadZgqk() {
        removeAllSubViews()
                
        var lastI: TaskCompletionRateItemView?
        
        var sortDatas: [BaglByDeptWdModel] = []
        
        for (index, record) in zgqkDatas.enumerated() {
            if index < 5 {
                sortDatas.append(record)
            }
        }
        
        if isMore == true {
            sortDatas.removeAll()
            sortDatas.append(contentsOf: zgqkDatas)
        }
        
        for (index, record) in sortDatas.enumerated() {
            let itemV = TaskCompletionRateItemView()    // 网点名称
            itemV.reloadData(withModal: record)
            itemV.ctl.tag = index
            itemV.ctl.addTarget(self, action: #selector(onSelectedZgqk), for: .touchUpInside)
            addSubview(itemV)
            if index == sortDatas.count - 1 {
                itemV.snp.makeConstraints { make in
                    make.left.right.equalToSuperview()
                    if lastI == nil {
                        make.top.equalTo(self.snp.top).offset(20)
                    } else {
                        make.top.equalTo(lastI!.snp.bottom).offset(20)
                    }
                    if (zgqkDatas.count <= 5 || isMore == true) {
                        make.bottom.equalToSuperview()
                    }
                }
            } else {
                itemV.snp.makeConstraints { make in
                    make.left.right.equalToSuperview()
                    if lastI == nil {
                        make.top.equalTo(self.snp.top).offset(20)
                    } else {
                        make.top.equalTo(lastI!.snp.bottom).offset(20)
                    }
                }
            }
            lastI = itemV
        }
        
        if zgqkDatas.count > 5 && isMore == false {
            let moreBtn = UIButton(type: .custom)
            moreBtn.setTitleColor(.hex("#B1B1B1"), for: .normal)
            moreBtn.setTitle("查看更多", for: .normal)
            moreBtn.titleLabel?.font = .systemFont(ofSize: 14)
            moreBtn.addTarget(self, action: #selector(loadMore), for: .touchUpInside)
            addSubview(moreBtn)
            moreBtn.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(lastI!.snp.bottom).offset(20)
                make.height.equalTo(20)
                make.bottom.equalToSuperview()
            }
        }
    }
}

class SecurityStatisticsView: UIScrollView {
    let basicBV = UIView.createBase()
    let baseTV = TitleItemView()
    let deptBtn = BSDeptStiscControl()
    let customV = BSCustomDateView(withType: .subTitle)
    let segmentedC = ScrollableSegmentedControl()
    let summaryV = BSStatisSummaryView()

    let contenV = UIView()
    let lzqkV = SpsLzqkView()
    let zgqkV = SpsZgqkView()
    
    let rateBV = UIView.createBase()
    let taskV = TaskCompletionRateView()
    
    var baglModel: BaglByDeptModel?
    var balzModel: CommonScaleByDeptModal?
    
    weak var sDelegate: SecurityStatisticsViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        keyboardDismissMode = .interactive
        showsVerticalScrollIndicator = false
        bounces = true
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func update(withWdwcqk wdwcqk: WdwcqkModel) {
        summaryV.update(withData: wdwcqk)
    }
    
    // MARK: - Datas
    func reloadData(deptName: String? = nil, date: String? = nil, type: CustomDateEnum? = nil, baglModel: BaglByDeptModel? = nil, balzModel: CommonScaleByDeptModal? = nil) {
        if deptName != nil {
            deptBtn.deptName = deptName!
        }
        
        if date != nil {
            customV.resetUI(date: date, type: type)
        }
        
        if baglModel != nil {
            self.baglModel = baglModel
            zgqkV.reloadData(withModels: baglModel?.wdList)
        }
        
        if balzModel != nil {
            self.balzModel = balzModel
            lzqkV.reloadData(withModels: balzModel?.wdList)
            deptBtn.depts = balzModel?.wdList ?? []
        }
        
        updateUI()
    }
    
    func reloadLzqk() {
        customV.subValue = "整体完成率: \(balzModel?.zwcl ?? "0")%"
        taskV.reloadData(balzModel?.zxList)
        taskV.title = balzModel?.title ?? "任务完成率"
        
        if zgqkV.superview != nil {
            zgqkV.removeFromSuperview()
        }
        
        if lzqkV.superview == nil {
            contenV.addSubview(lzqkV)
        }
        
        lzqkV.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func reloadZgqk() {
        customV.subValue = "整体在岗率: \(baglModel?.zgl ?? "0")%"
        taskV.reloadData(baglModel?.zxList)
        taskV.title = baglModel?.title ?? "任务完成率"
        
        if lzqkV.superview != nil {
            lzqkV.removeFromSuperview()
        }
        
        if zgqkV.superview == nil {
            contenV.addSubview(zgqkV)
        }
        
        zgqkV.snp.remakeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func updateUI() {
        let index = segmentedC.selectedSegmentIndex
        if index == 0 {
            reloadLzqk()
        }
        if index == 1 {
            reloadZgqk()
        }
    }
    
    @objc func segmentSelected(sender: ScrollableSegmentedControl) {
        updateUI()
    }
    
    func setupUI() {
        addSubview(basicBV)
        basicBV.snp.makeConstraints { make in
            make.top.equalTo(self.snp.top).offset(10)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenWidth - 20)
        }
        
        basicBV.addSubview(baseTV)
        baseTV.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(46)
        }
        
        basicBV.addSubview(deptBtn)
        deptBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(baseTV.snp.bottom)
            make.height.equalTo(35)
        }
        
        basicBV.addSubview(summaryV)
        summaryV.snp.remakeConstraints { (make) -> Void in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(deptBtn.snp.bottom).offset(16)
            make.height.equalTo(60)
        }

        customV.subValue = "整体完成率: 0%"
        basicBV.addSubview(customV)
        customV.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(summaryV.snp.bottom).offset(20)
            make.height.equalTo(35)
        }
        
        segmentedC.tintColor = .primary
        segmentedC.underlineSelected = true
        segmentedC.segmentContentColor = .black
        segmentedC.selectedSegmentContentColor = .primary
        segmentedC.backgroundColor = .white
        segmentedC.addTarget(self, action: #selector(segmentSelected(sender:)), for: .valueChanged)
        let normalAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        let highlightAttrs =  [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        let selectAttrs = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)]
        segmentedC.setTitleTextAttributes(normalAttrs, for: .normal)
        segmentedC.setTitleTextAttributes(highlightAttrs, for: .highlighted)
        segmentedC.setTitleTextAttributes(selectAttrs, for: .selected)
        basicBV.addSubview(segmentedC)
        segmentedC.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(customV.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(48)
        }
        
        segmentedC.insertSegment(withTitle: "履职情况", at: 0)
        segmentedC.insertSegment(withTitle: "在岗情况", at: 1)
        segmentedC.selectedSegmentIndex = 0
        
        basicBV.addSubview(contenV)
        contenV.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentedC.snp.bottom)
            make.bottom.equalToSuperview().offset(-20)
        }
        
        setupRateView()
        
        zgqkV.sDelegate = self
        lzqkV.sDelegate = self
    }
    
    func setupRateView() {
        addSubview(rateBV)
        rateBV.snp.makeConstraints { make in
            make.top.equalTo(basicBV.snp.bottom).offset(10)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenWidth - 20)
            make.bottom.equalToSuperview().offset(-40)
        }
        
        taskV.title = "过去6个月任务完成率"
        rateBV.addSubview(taskV)
        taskV.snp.makeConstraints { make in
            make.top.equalTo(rateBV.snp.top).offset(22)
            make.centerX.equalToSuperview()
            make.height.equalTo(322)
            make.width.equalTo(ScreenWidth - 20)
            make.bottom.equalToSuperview().offset(-20)
        }
    }
}

extension SecurityStatisticsView: SecurityStatisticsViewDelegate {
    func handleLzqkSelected(_ modal: TaskDeptRateModal) {
        sDelegate?.handleLzqkSelected(modal)
    }
    
    func handleZgqkSelected(_ modal: BaglByDeptWdModel) {
        sDelegate?.handleZgqkSelected(modal)
    }
}
